K.I.A.Derouiche
Mars 24, 2018 Free Djelfa
Djelfa, Algerie


créé par F Perez(Photo) (chercheur au Berkeley Institute for Data Science) en 2001.

Trois méthodes d'installations:
IPython un shell python évolué:
Avec complétation automatique et coloration syntaxique.
IPython affiche le résultat de la derniére expression évaluée si elle ne vaut pas None
Available line magics: %alias %alias_magic %autocall %autoindent %automagic %bookmark %cat %cd %clear %colors %config %cp %cpaste %debug %dhist %dirs %doctest_mode %ed %edit %env %gui %hist %history %killbgscripts %ldir %less %lf %lk %ll %load %load_ext %loadpy %logoff %logon %logstart %logstate %logstop %ls %lsmagic %lx %macro %magic %man %matplotlib %mkdir %more %mv %notebook %page %paste %pastebin %pdb %pdef %pdoc %pfile %pinfo %pinfo2 %popd %pprint %precision %profile %prun %psearch %psource %pushd %pwd %pycat %pylab %quickref %recall %rehashx %reload_ext %rep %rerun %reset %reset_selective %rm %rmdir %run %save %sc %set_env %store %sx %system %tb %time %timeit %unalias %unload_ext %who %who_ls %whos %xdel %xmode
Available cell magics: %%! %%HTML %%SVG %%bash %%capture %%debug %%file %%html %%javascript %%js %%latex %%markdown %%perl %%prun %%pypy %%python %%python2 %%python3 %%ruby %%script %%sh %%svg %%sx %%system %%time %%timeit %%writefile
Automagic is ON, % prefix IS NOT needed for line magics.
En lançant la commande IPython on travaille directement avec IPython, via stdin, stdout et stderr
Outer l'économie de ressources, cela permet de l'utiliser comme un shell systéme
# Demarrer le logging de la session
%logstart
#Etat de la session
%logstate
#Stoppé une session
%logoff
Logging hasn't been started yet (use logstart for that). %logon/%logoff are for temporarily starting and stopping logging for a logfile which already exists. But you must first start the logging process with %logstart (optionally giving a logfile name).
# Historique de la session
%history #or %hist
# Mesurer le temps d'exécution
S = [x**2 for x in range(10)]
%timeit M = [x for x in S if x % 2 == 0]
891 ns ± 31.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
La commande shell commence par un point d'exclamation. Est la ligne est passé au shell du système
# avec la commande **!**
In [3]: ! du -h /etc
IPython propose une alternative commode à la commande help() de python avec la syntaxe ? On peut même consulter le code source (si présent) avec ??
import io
io.BytesIO?
Init signature: io.BytesIO(initial_bytes=b'') Docstring: Buffered I/O implementation using an in-memory bytes buffer. Type: type
## Je souhaite calculer pour la valeur x = 2.0 avec SymPy et NumPy
from IPython.display import display, Math, Latex
display(Math(r'y = \sqrt{log(1+x^{2})+\frac{x^{\sin(2\pi x)}}{\tanh(2.)}}'))
C'est une interface web interactive offrant toutes les commodités du shell
IPython avec un affichage riche(graphique et texte riche).

Depuis la version 4, le projet ipython à été divsé en :


IPython Kernel supporte plus de 50 langage de programmation utiliser et mélanger dans une même interface: Python, R, JavaScript, Ruby, Perl, C, Julia, Fortran, Matlab ou Mathematica, SQLite et SQL.
A premiére vue, le shell IPython et la console Jupyter sont identiques, ils ont les memes fonctionalités utilisateurs lancer:
Cependant, la commande jupyter console:
plusieurs consoles Jupyter peuvent partager le meme noyau
En lançant la commande ipython on travaille directement avec IPython, via stdin, stdout et stderr.
Outre l'économie de ressources, cela permet de l'utiliser comme un shell système
En mode console, on à accès à toutes les fonctionnalités du noyau IPython , à l'exception de l'affichage graphique riche des objets qui n'est exploitable qu'avec le Notebook(et dans une moindre mesure avec jupyter qtconsole)

A premiére vue, le shell IPython et la console Jupyter sont identiques, ils ont les memes fonctionnalités utilisateur.
Avec le notebook du Jupyter on a :
Le document ainsi crée est enregistré au format .ipynb qui est au format JSON.
Démonstration


IPython offre la possiblité aux objets Python de définir des représentations autres que le simple
#Utilisation d'objet Python pour l'affichage
from IPython.display import Image
img = Image("images/logo_collage.png")
img
print(img._repr_png_()[:100])
iVBORw0KGgoAAAANSUhEUgAABVYAAACaCAYAAABCKxN6AAFJ10lEQVR42uy9h1MUXRfue/6Fc2/dc2/dqlNffg1gzjkCEkRRQcRA
from IPython.display import Audio
song = Audio("./data/001_Debutant_CD1.mp3")
song
print(song._repr_html_()[:200])
<audio controls="controls" >
<source src="data:audio/mpeg;base64,SUQzAwAAAAAhdlRQRTIAAAAOAAAATWljaGVsIFRob21hc1RZRVIAAAAFAAAAMjAwN1RSQ0sAAAADAAAAMDFUUFVCAAAAHgAAAE
from IPython.display import YouTubeVideo
YouTubeVideo("8uWRVh58KdQ")
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0.1, 20, 200)
fig, axe = plt.subplots(figsize=(12, 8))
axe.plot(x, np.sin(x)/x)
[<matplotlib.lines.Line2D at 0x7fb4a8122518>]
%matplotlib notebook
fig, axe = plt.subplots(figsize=(12, 8))
axe.plot(x, np.sin(x)/x)
[<matplotlib.lines.Line2D at 0x7fb4a7f4c710>]
l’utilisation de la librairie Pandas rend la lecture de certains formats, le regroupement de données et quelques traitements statistiques trés simples.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.read_excel('data/stock.xlsx')
df.head(3)
| VIN | NUM ORDRE | CODE | MODEL | ETAT | ARRIVAGE | LOCALISATION | COULEUR | |
|---|---|---|---|---|---|---|---|---|
| 1 | Z226722 | 7090339.0 | 0A02 | R1200GS ADV | NaN | NaN | NaN | RACING RED MATT |
| 2 | Z721037 | 8430547.0 | 0J11 | R NINET PURE | PRODUIT | PROTOTYPE | NaN | GRIS ALUMINUM |
| 3 | Z735434 | 8430548.0 | 0J21 | R NINET RACER | NaN | PROTOTYPE | SHOW-ROOM | BLANC |
df.isnull()
| VIN | NUM ORDRE | CODE | MODEL | ETAT | ARRIVAGE | LOCALISATION | COULEUR | |
|---|---|---|---|---|---|---|---|---|
| 1 | False | False | False | False | True | True | True | False |
| 2 | False | False | False | False | False | False | True | False |
| 3 | False | False | False | False | True | False | False | False |
| 4 | False | False | False | False | False | False | False | False |
| 5 | False | False | False | False | False | False | True | False |
| 6 | False | False | False | False | False | False | False | False |
| 7 | False | False | False | False | False | False | False | False |
| 8 | False | False | False | False | False | False | False | False |
| 9 | False | False | False | False | False | True | False | False |
| 10 | False | False | False | False | False | False | True | False |
| 11 | False | False | False | False | False | False | False | False |
| 12 | False | False | False | False | False | False | True | False |
| 13 | False | False | False | False | False | False | True | False |
| 14 | False | False | False | False | True | False | True | False |
| 15 | False | False | False | False | False | True | False | False |
| 16 | False | False | False | False | False | True | True | False |
| 17 | False | False | False | False | False | True | True | False |
| 18 | True | False | False | False | False | True | True | False |
| 19 | True | True | False | False | False | True | True | False |
| 20 | False | False | False | False | False | False | True | False |
| 21 | False | False | False | False | False | False | True | False |
| 22 | False | False | False | False | False | False | True | False |
| 23 | False | False | False | False | False | False | True | False |
| 24 | False | False | False | False | False | False | True | False |
| 25 | False | False | False | False | False | False | True | False |
| 26 | False | False | False | False | False | False | True | False |
| 27 | False | False | False | False | False | False | True | False |
| 28 | False | False | False | False | False | False | True | False |
| 29 | False | False | False | False | False | False | True | False |
| 30 | False | False | False | False | False | False | True | False |
| ... | ... | ... | ... | ... | ... | ... | ... | ... |
| 84 | True | False | False | False | False | True | True | False |
| 85 | True | False | False | False | False | True | True | False |
| 86 | True | False | False | False | False | True | True | False |
| 87 | True | False | False | False | False | True | True | False |
| 88 | True | False | False | False | False | True | True | False |
| 89 | True | False | False | False | False | True | True | False |
| 90 | True | False | False | False | False | True | True | False |
| 91 | True | False | False | False | False | True | True | False |
| 92 | True | False | False | False | False | True | True | False |
| 93 | True | False | False | False | False | True | True | False |
| 94 | True | False | False | False | False | True | True | False |
| 95 | True | False | False | False | False | True | True | False |
| 96 | True | False | False | False | False | True | True | False |
| 97 | True | False | False | False | False | True | True | False |
| 98 | True | False | False | False | False | True | True | False |
| 99 | True | False | False | False | False | True | True | False |
| 100 | True | False | False | False | False | True | True | False |
| 101 | True | False | False | False | False | True | True | False |
| 102 | True | False | False | False | False | True | True | False |
| 103 | True | False | False | False | False | True | True | False |
| 104 | True | False | False | False | False | True | True | False |
| 105 | True | False | False | False | False | True | True | False |
| 106 | True | False | False | False | False | True | True | False |
| 107 | True | False | False | False | False | True | True | False |
| 108 | True | False | False | False | False | True | True | False |
| 109 | True | False | False | False | False | True | True | False |
| 110 | True | False | False | False | False | True | True | False |
| 111 | True | False | False | False | False | True | True | False |
| 112 | True | False | False | False | False | True | True | False |
| 113 | True | False | False | False | False | True | True | False |
113 rows × 8 columns
%matplotlib inline
data = pd.read_csv("./example/hubble_data.csv")
data.head()
File "<ipython-input-18-11b5bd12e64d>", line 4 [ressource](https://github.com/shantnu/Intro-to-Pandas) ^ SyntaxError: invalid syntax
headers = ["dist","rec_vel"]
data_no_headers = pd.read_csv("./example/hubble_data_no_headers.csv", names = headers)
data_no_headers.head()
| dist | rec_vel | |
|---|---|---|
| 0 | 0.032 | 170 |
| 1 | 0.034 | 290 |
| 2 | 0.214 | -130 |
| 3 | 0.263 | -70 |
| 4 | 0.275 | -185 |
Selectionné d'une colonne
data_no_headers["dist"]
0 0.032 1 0.034 2 0.214 3 0.263 4 0.275 5 0.275 6 0.450 7 0.500 8 0.500 9 0.630 10 0.800 11 0.900 12 0.900 13 0.900 14 0.900 15 1.000 16 1.100 17 1.100 18 1.400 19 1.700 20 2.000 21 2.000 22 2.000 23 2.000 Name: dist, dtype: float64
Jouer avec les index
data.set_index("distance", inplace= True)
data.head()
data.plot()
plt.show()
data = pd.read_csv("./example/wages_hours.csv")
data.head()
| HRS RATE ERSP ERNO NEIN ASSET AGE DEP RACE SCHOOL | |
|---|---|
| 0 | 2157\t2.905\t1121\t291\t380\t7250\t38.5\t2.340... |
| 1 | 2174\t2.970\t1128\t301\t398\t7744\t39.3\t2.335... |
| 2 | 2062\t2.350\t1214\t326\t185\t3068\t40.1\t2.851... |
| 3 | 2111\t2.511\t1203\t49\t117\t1632\t22.4\t1.159\... |
| 4 | 2134\t2.791\t1013\t594\t730\t12710\t57.7\t1.22... |
filter l'affichage
data = pd.read_csv("./example/wages_hours.csv", sep = "\t")
data.head()
| HRS | RATE | ERSP | ERNO | NEIN | ASSET | AGE | DEP | RACE | SCHOOL | |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 2157 | 2.905 | 1121 | 291 | 380 | 7250 | 38.5 | 2.340 | 32.1 | 10.5 |
| 1 | 2174 | 2.970 | 1128 | 301 | 398 | 7744 | 39.3 | 2.335 | 31.2 | 10.5 |
| 2 | 2062 | 2.350 | 1214 | 326 | 185 | 3068 | 40.1 | 2.851 | * | 8.9 |
| 3 | 2111 | 2.511 | 1203 | 49 | 117 | 1632 | 22.4 | 1.159 | 27.5 | 11.5 |
| 4 | 2134 | 2.791 | 1013 | 594 | 730 | 12710 | 57.7 | 1.229 | 32.5 | 8.8 |
l'âge par rapport au taux (salaire)
data2 = data[["AGE", "RATE"]]
data2.head()
| AGE | RATE | |
|---|---|---|
| 0 | 38.5 | 2.905 |
| 1 | 39.3 | 2.970 |
| 2 | 40.1 | 2.350 |
| 3 | 22.4 | 2.511 |
| 4 | 57.7 | 2.791 |
trier par valeur
data_sorted = data2.sort_values(["AGE"])
data_sorted.head()
| AGE | RATE | |
|---|---|---|
| 3 | 22.4 | 2.511 |
| 27 | 37.2 | 3.015 |
| 31 | 37.4 | 1.901 |
| 33 | 37.5 | 1.899 |
| 32 | 37.5 | 3.009 |
trier par index
data_sorted.set_index("AGE", inplace=True)
data_sorted.head()
| RATE | |
|---|---|
| AGE | |
| 22.4 | 2.511 |
| 37.2 | 3.015 |
| 37.4 | 1.901 |
| 37.5 | 1.899 |
| 37.5 | 3.009 |
le taux augmente jusqu'à l'âge de 35 ans, puis il varie considérablement.
data_sorted.plot()
plt.show()
from sympy import *
# Initialize notebook printing
init_printing()
integrate(x**2 * exp(x) * cos(x), x)
from sympy.integrals import laplace_transform
from sympy.abc import t, s, a
laplace_transform(t**a, t, s)
Dans ces cellules on peut saisir du texte aves des balises de lise en forme:
Une extension IPython pour ajouter encore plus d'interactivité à nos Notebooks.
Les IPywidgets sont des éléments graphiques permettant de piloter des paramétres de fonctions
La clé réside dans la commande interact
from ipywidgets import interact
from ipywidgets import *
from IPython.display import display
w = IntSlider()
display(w, w)
def f(x):
print(x)
interact(f, x=10)
<function __main__.f>
interact(f, x=True) #Or False
<function __main__.f>
valeur booléen
interact(f, x='text')
<function __main__.f>
from ipywidgets import interact
t = np.arange(0.0, 1.0, 0.01)
x = np.linspace(0, 2*np.pi, 100)
def pltsin(f):
plt.plot(x, sin(2*np.pi*t*f))
plt.show()
interact(pltsin, f=(1, 10, 0.1))
t
array([0. , 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1 ,
0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.18, 0.19, 0.2 , 0.21,
0.22, 0.23, 0.24, 0.25, 0.26, 0.27, 0.28, 0.29, 0.3 , 0.31, 0.32,
0.33, 0.34, 0.35, 0.36, 0.37, 0.38, 0.39, 0.4 , 0.41, 0.42, 0.43,
0.44, 0.45, 0.46, 0.47, 0.48, 0.49, 0.5 , 0.51, 0.52, 0.53, 0.54,
0.55, 0.56, 0.57, 0.58, 0.59, 0.6 , 0.61, 0.62, 0.63, 0.64, 0.65,
0.66, 0.67, 0.68, 0.69, 0.7 , 0.71, 0.72, 0.73, 0.74, 0.75, 0.76,
0.77, 0.78, 0.79, 0.8 , 0.81, 0.82, 0.83, 0.84, 0.85, 0.86, 0.87,
0.88, 0.89, 0.9 , 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98,
0.99])
\$ pip install ipywidgets
\$ jupyter nbextension enable --py --sys-prefix widgetsnbextension

JupyterLab dispose d'une option pour liste les extensions:
$ jupyterlab labextension list
Pour installer une extension pour jupyter
$ jupyter labextension install jupyterlab_voyager
jupyter labextension disable
jupyter labextension enable
https://jupyterlab.readthedocs.io/en/latest/developer/extension_dev.html
$ jupyter kernelspec list
Available kernels:
bash /home/kiad/.local/share/jupyter/kernels/bash
python3 /home/kiad/.local/share/jupyter/kernels/python3
octave /home/kiad/Atelier/EmulPy/share/jupyter/kernels/
scilab /home/kiad/Atelier/EmulPy/share/jupyter/kernels/scilab
coarray-fortran /usr/local/share/jupyter/kernels/coarray-fortran
python2 /usr/share/jupyter/kernels/python2
sagemath /usr/share/jupyter/kernels/sagemath
L'outil nbconvert est un outil en ligne de commandes qui permet de convertir les fichiers .ipynb dans un des formats supportés: HTML, PDF via LaTeX, diapositives(reveal.js), script, markdown, ReStructured Text.
jupyter nbconvert --to pdf votre_fichier.ipynb
jupyter nbconvert --to html --template base votre_fichier.ipynb
jupyter nbconvert slides.ipynb --to slides --post serve --ServePostProcessor.reveal_cdn="http://cdn.jsdelivr.net/reveal.js/2.5.0"
Démonstration

Avec d'autres utilisateurs de jupyter:
# Questions?